package com.boolib.animate.framework.service.base.impl;

import com.boolib.animate.commons.base.BaseCurdService;
import com.boolib.animate.framework.entity.FileInfo;
import com.boolib.animate.framework.service.extend.IUploadService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 功能描述：图片上传业务 同步数据库
 *
 * @author Administrator
 * @description
 * @since 2019/12/27 16:11
 */
@Slf4j
@Service
public class FileInfoService  extends BaseCurdService<FileInfo>  {

	@Autowired
	private IUploadService iUploadService;

	@Value("${system.domain}")
	private String domain;


	/**
	 *
	 * @param path
	 * @param multipartFile
	 * @param bizType
	 * @return
	 * @throws IOException
	 * @throws FileUploadException
	 */

	@Transactional
	public String uploadImage(String path, MultipartFile multipartFile, Integer bizType) throws IOException, FileUploadException {

		String newName = iUploadService.uploadImage(path, multipartFile);

		try {
			saveSelective(FileInfo.builder()

					.bizType(bizType)
					.filePath(path)
					.fileSize(String.valueOf(multipartFile.getSize()))
					.newName(newName)
					.fileType(multipartFile.getContentType())
					.originalName(multipartFile.getOriginalFilename())
					.relativePath(newName)
					.build());

		}catch (Exception ex){
			iUploadService.removeOne(path,newName);
			throw new FileUploadException(ex.getMessage());
		}

		return domain+"/"+newName;
	}


	public String uploadImage(String path, MultipartFile multipartFile) throws IOException, FileUploadException {

		String newName = iUploadService.uploadImage(path, multipartFile);

		try {
			saveSelective(FileInfo.builder()
					.filePath(path)
					.fileSize(String.valueOf(multipartFile.getSize()))
					.newName(newName)
					.fileType(multipartFile.getContentType())
					.originalName(multipartFile.getOriginalFilename())
					.relativePath(newName)
					.build());

		}catch (Exception ex){
			iUploadService.removeOne(path,newName);
			throw new  FileUploadException(ex.getMessage());
		}

		return domain+"/"+newName;
	}


	public FileInfo queryByName(String name) {
		return FileInfo.builder().newName(name).build();
	}
}
